<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <div class="text item">
      <el-form ref="form" label-width="80px" :model="userInfo" :rules="formRules">
        <el-form-item label="登录名称">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUser">提交修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/APl/user.js'
export default {
  data() {
    return {
      userInfo: {
        // username: this.$store.state.user.user.username,
        // nickname: this.$store.state.user.user.nickname,
        // email: this.$store.state.user.user.email,
        // id: this.$store.state.user.user.id
        ...this.$store.state.user.user
      },
      formRules: {
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称为1-10位非字符串组成',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    updateUser() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const { data: res } = await updateUserAPI(this.userInfo)
          if (res.code === 0) {
            this.$message.success(res.message)
            this.$store.dispatch('user/getUser')
          } else {
            this.$message.error(res.message)
          }
        }
      })
    },
    reset() {
      this.$refs.form.resetFields()
      this.userInfo = Object.assign({}, this.$store.state.user.user)
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  font-size: 13px;
}
.el-form {
  width: 500px;
}
</style>
